package cn.hd01.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.domain.Specifications;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import cn.hd01.repository.RebateBookRepository;
import cn.hd01.repository.entity.RebateBook;
import cn.hd01.service.RebateBookService;

@Service
public class RebateBookServiceImpl extends BaseServiceImpl<RebateBook, Integer> implements RebateBookService {

	private RebateBookRepository repository;

	@Autowired
	public RebateBookServiceImpl(RebateBookRepository repository) {
		super(repository);
		this.repository = repository;
	}

	@Override
	public Page<RebateBook> findAll(final RebateBook rebateBook,
			Pageable pageable) {
		if (rebateBook == null) {
			return repository.findAll(pageable);
		}

		return repository.findAll(Specifications.where(new Specification<RebateBook>() {
			@Override
			public Predicate toPredicate(Root<RebateBook> r, CriteriaQuery<?> q, CriteriaBuilder cb) {
				List<Predicate> predicates = new ArrayList<Predicate>();
				
				if(StringUtils.hasText(rebateBook.getType())){
					predicates.add(cb.equal(r.get("type").as(String.class), rebateBook.getType()));
				}
				
				if(rebateBook.getRefId() != null){
					predicates.add(cb.equal(r.get("refId").as(Integer.class), rebateBook.getRefId()));
				}
				
				if (StringUtils.hasText(rebateBook.getBeginDate())) {
					predicates.add(cb.greaterThan(r.get("createTime").as(String.class), rebateBook.getBeginDate()));
				}
				
				if (StringUtils.hasText(rebateBook.getEndDate())) {
					predicates.add(cb.lessThan(r.get("createTime").as(String.class), rebateBook.getEndDate()));
				}
				
				return cb.and(predicates.toArray(new Predicate[] {}));
			}
		}), pageable);
	}

	@Override
	public Page<Object> findAgent(Integer distributorId, Pageable pageable) {
		Integer count = repository.countAgent(distributorId);
		List<Object> list = new ArrayList<Object>();
		if(count != 0){
			list = repository.findAgent(distributorId, pageable.getPageNumber() * pageable.getPageSize(), pageable.getPageNumber() * pageable.getPageSize() + pageable.getPageSize());
		}
		return new PageImpl<Object>(list, pageable, count);
	}

}
